﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookShop3Tables.Models;
using BookShop3Tables.ViewModels;
using PagedList;

namespace BookShop3Tables.Controllers
{ 
    public class BookController : Controller
    {
        private BookContext db = new BookContext();

        //
        // GET: /Book/

        public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Genre desc" : "";
            
            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;

            var books = from a in db.Books
                          select a;
            
            if (!String.IsNullOrEmpty(searchString))
            {
                books = books.Where(a => a.Name.ToUpper().Contains(searchString.ToUpper())
                    || a.Author.FirstName.ToUpper().Contains(searchString.ToUpper())
                    || a.Author.LastName.ToUpper().Contains(searchString.ToUpper()));
               
            }
            switch (sortOrder)
            {
                case "Genre desc":
                    books = books.OrderByDescending(a => a.Category.Name);
                    break;               
                default:
                    books = books.OrderBy(a => a.Category.Name);
                    break;
            }
            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(books.ToPagedList(pageNumber, pageSize));
        }

        //
        // GET: /Book/Details/5

        public ViewResult Details(int id)
        {
            Book book = db.Books.Find(id);
            return View(book);
        }

        //
        // GET: /Book/Create

        public ActionResult Create()
        {
            PopulateAuthorDropDownList();
            PopulateCategoryDropDownList();
            return View();
        } 

        //
        // POST: /Book/Create

        [HttpPost]
        public ActionResult Create(Book book)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Books.Add(book);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            PopulateAuthorDropDownList(book.PersonID);
            PopulateCategoryDropDownList(book.CategoryID);
            return View(book);
        }
        
        //
        // GET: /Book/Edit/5
 
        public ActionResult Edit(int id)
        {
            Book books = db.Books.Find(id);
            PopulateAuthorDropDownList(books.PersonID);
            PopulateCategoryDropDownList(books.CategoryID);
            return View(books);
        }

        //
        // POST: /Book/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            var bookUpdate = db.Books
                .Include(i => i.Category)               
                .Where(i => i.BookID == id)
                .Single();
            if (TryUpdateModel(bookUpdate, "", null, new string[] { "Category", "FirstName", "LastName" }))
            {
                try
                {
                    if (String.IsNullOrEmpty(bookUpdate.Category.Name))
                    {}
                    if (String.IsNullOrWhiteSpace(bookUpdate.Author.FirstName))
                    {
                        bookUpdate.Author.FirstName = "FirstName";
                    }
                    if (String.IsNullOrWhiteSpace(bookUpdate.Author.LastName))
                    {
                        bookUpdate.Author.LastName = "LastName";
                    }
                    db.Entry(bookUpdate).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (DataException)
                {
                    ModelState.AddModelError("", "Unable to save changes");
                    return View();
                }
            }
            return View(bookUpdate);
           
        }

        private void PopulateCategoryDropDownList(object selectedCategory = null)
        {
            var categoriesQuery = from d in db.Categories
                                   orderby d.Name
                                   select d;
            ViewBag.CategoryID = new SelectList(categoriesQuery, "CategoryID", "Name", selectedCategory);
        }

        private void PopulateAuthorDropDownList(object selectedAuthor = null)
        {
            var authorQuery = from d in db.People                                                          
                              //orderby d.FullName
                              select d;
            ViewBag.PersonID = new SelectList(authorQuery, "PersonID", "FullName", selectedAuthor);
        }

       

        //
        // GET: /Book/Delete/5
 
        public ActionResult Delete(int id, bool? saveChangesError)
        {
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Unable to save changes";
            }
            return View(db.Books.Find(id));
        }

        //
        // POST: /Book/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                Book bookToDelete = new Book() { BookID = id };
                db.Entry(bookToDelete).State = EntityState.Deleted;
                db.SaveChanges();
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                return RedirectToAction("Delete",
                    new System.Web.Routing.RouteValueDictionary { 
                { "id", id }, 
                { "saveChangesError", true } });
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}